//
//  SEPrescriptionDrugPickViewModel.swift
//  SmartEyeForDoctor
//
//  Created by QDSG on 2021/5/11.
//

import UIKit

class SEPrescriptionDrugPickViewModel: SEBaseViewModel {
    var drugPickList = [SEPrescriptionDrugPick]()
    var drugPickModel = SEPrescriptionDrugPick()
    
    convenience init(drugPickModel: SEPrescriptionDrugPick) {
        self.init()
        self.drugPickModel = drugPickModel
    }
    
    var numberOfRows: Int { drugPickList.count }
    
    func viewModel(at indexPath: IndexPath) -> SEPrescriptionDrugPickViewModel {
        return SEPrescriptionDrugPickViewModel(drugPickModel: drugPickList[indexPath.row])
    }
    
    var cellHeight: CGFloat { return 70 }
    
    var content: String = ""
    
    var drugModel = SEPrescriptionDrug()
    
    var loadDetailOfDrugHandler: ((SEHttpStatus) -> Void)?
    
    var confirmEnabled: Bool {
        return drugModel.drugDose?.isEmpty == false &&
            drugModel.drugFrequency?.isEmpty == false &&
            drugModel.drugPosition?.isEmpty == false &&
            drugModel.drugUsing?.isEmpty == false &&
            drugModel.drugNumber?.isEmpty == false
    }
}

// MARK: - 网络请求

extension SEPrescriptionDrugPickViewModel {
    /// 获取处方药品列表
    func getListOfPrescriptionDrug(_ more: Bool) {
        page = more ? page + 1 : 1
        SEHttpManager.shared.request(SEPrescriptionAPI.listOfPrescriptionDrug(content: content, pageNum: page, pageSize: pageSize), model: SEPrescriptionDrugPickList.self) { (model, httpStatus) in
            switch httpStatus {
            case .success:
                if !more {
                    self.drugPickList = model?.list ?? self.drugPickList
                } else {
                    self.drugPickList.append(contentsOf: model?.list ?? [])
                }
                self.hasMore = model?.totalPage ?? 0 > self.page
            case .auth(let message), .failure(let message):
                SEHUD.showError(message: message, position: .center)
            }
            self.updateData?(httpStatus)
        }
    }
    
    /// 获取处方药品详情
    func getDetailOfPrescriptionDrug(id: String) {
        withLoading = true
        SEHttpManager.shared.request(SEPrescriptionAPI.detailOfPrescriptionDrug(id: id), model: SEPrescriptionDrug.self, withLoading: withLoading) { (model, httpStatus) in
            switch httpStatus {
            case .success:
                self.drugModel = model ?? self.drugModel
                self.drugModel.medicineId = model?.id
            case .auth(let message), .failure(let message):
                SEHUD.showError(message: message)
            }
            self.loadDetailOfDrugHandler?(httpStatus)
        }
    }
}
